package com.client.yushi;

import com.client.entity.PassAuthor;
import com.client.entity.auth.Command;
import com.client.entity.auth.Operator;
import com.client.mapper.AuthorityDao;
import com.client.mapper.CommandDao;
import com.client.mapper.OperatorDao;
import com.client.mapper.PassAuthorDao;
import com.client.utils.AESutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//设备端的对外接口
@Component
public class Util {
    @Autowired
    AuthorityDao authorityDao;
    @Autowired
    CommandDao commandDao;
    @Autowired
    OperatorDao operatorDao;
    @Autowired
    PassAuthorDao passAuthorDao;

    //查询某人员是否有该权限
    public boolean isAuthorised(String operator, String command) {
        Operator op = operatorDao.queryByName(operator);
        if (op == null)
            return false;

        Command command1 = commandDao.queryByURL(command);
        if (command1 == null)
            return false;

        return authorityDao.query(op.getId(), command1.getId()) != null;
    }

    //使用某人员的密钥对消息进行加密
    public byte[] encrypt(String operator, byte[] msg) {
        PassAuthor author = passAuthorDao.queryByName(operator);
        if (author != null) {
            try {
                return AESutil.encrypt(msg, author.getK());
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }

    //使用某人员的密钥对消息进行解密
    public byte[] decode(String operator, byte[] msg) {
        PassAuthor author = passAuthorDao.queryByName(operator);
        if (author != null) {
            try {
                return AESutil.decode(msg, author.getK());
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }

    //获取与某人通信的密钥
    public byte[] getKey(String operator) {
        PassAuthor author = passAuthorDao.queryByName(operator);
        if (author != null)
            return author.getK();
        return null;
    }
}
